<template>
  <!-- <TagsView/> -->

    <!-- 年度考核题库 题库管理-->
    <div class="container">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/examineManage/digitalExamine/annual' }">年度考核题库</el-breadcrumb-item>
        <el-breadcrumb-item >题库管理</el-breadcrumb-item>
      </el-breadcrumb>
      <el-row class="" style="margin-bottom: 20px">
        <el-col :span="10" align="left">
          <el-input
            v-model="searchFrom.param"
            placeholder="指标名称/编号"
            style="width: 150px; margin-right: 15px"
            @change="search"
            clearable
          />
          <el-button class="ordinary" @click="search()">搜索</el-button>
        </el-col>
        <el-col :span="14" align="right">
          <el-button class="primary" @click="$router.go(-1)">返回</el-button>
          <el-button class="ordinary" @click="getExportBtn()">批量导出</el-button>
          <el-button type="primary" @click="downMb()">下载模板</el-button>
          <el-upload
            class="upload-demo"
            action="/fastDfs/file/upload"
            :on-success="handleSuccess"
            multiple :headers="data.headers"
            :limit="1"
            :show-file-list="false"
            :file-list="data.fileList">
            <el-button type="primary" @click="importMb()">模板导入</el-button>
          </el-upload>
          <!-- 锁定状态下不能显示删除与新建 -->
          <template v-if="status !== '已锁定'">
            <el-button type="danger" @click="handleDetect()">删除</el-button>
            <el-button type="primary" @click="handleAdd('add')">新建</el-button>
          </template>
          <el-button type="primary" @click="handleAssessment()">生成考核</el-button>
        </el-col>
      </el-row>
      <div>
        <el-table
          ref="multipleDevCreateRef"
          :data="data.table_list"
          style="width: 100%"
          row-key="id"
          v-loading="data.table_loading"
          @selection-change="selectionChange"
          @select="select"
          @select-all="selectAll"
          :default-expand-all="true"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
          <el-table-column
            type="selection"
            width="55"
            align="center"
            fixed="left"
          />
          <el-table-column prop="number" label="编号" width="160" align="left"  fixed="left" />
          <el-table-column prop="title" label="标题" align="center" width="160" fixed="left" />
          <el-table-column prop="classType_text" label="类型" align="center" width="160"></el-table-column>
          <el-table-column prop="questionType_text" label="题型" align="center" width="160"></el-table-column>
          <el-table-column prop="standardScore" label="分数" align="center" width="160" />
          <el-table-column prop="scoreMethod" label="计分方法"  align="center" width="220"></el-table-column>
          <el-table-column prop="createUsername" label="操作人" align="center" width="140"  />
          <el-table-column prop="modifyTime" label="编辑时间" align="center" width="180"  />
          <el-table-column prop="address" label="操作" align="center" width="220" fixed="right">
            <template #default="scope">
              <el-button type="primary"
                         v-if="status !== '锁定' && status !== '已锁定'"
                         @click="handleEdit(scope.row,'edit')">编辑</el-button>
              <el-button
                v-if="status !== '草稿'"
                @click="handleEdit(scope.row,'look')"
                >查看</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <AddDialog :handleRowData="data.handleRowData" :visible="data.modalVisible" @closeDialog="closeDialog" :addType="data.addType"/>

      <el-dialog
        v-model="data.assessmentVisible"
        :show-close="false"
        width="1100px"
        :title="'请选择生成考核的子公司'"
        class="dialog1"
        @close="data.searchIpt = ''"
      >
      <el-input placeholder="请输入关键字搜索" style="margin-bottom: 10px;" v-model="data.searchIpt" @input="changeIpt(data.searchIpt)"></el-input>
      <el-table
          ref="assessmentTable"
          v-loading="data.fustank"
          :data="data.table_assessment"
          style="width: 100%"
          row-key="id"
          @selection-change="selectionAssessment"
          :default-expand-all="true"
        >
          <el-table-column type="selection" width="55"  align="center" :reserve-selection="false"/>
          <el-table-column prop="companyName" label="公司名称"  align="center" />

      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button size="small" @click="closeAssessment">关闭</el-button>
          <el-button size="small" type="primary" @click="saveAssessment()">保存</el-button>
        </span>
      </template>
     </el-dialog>
    </div>
  </template>
  <script lang="ts" setup>
  import { ref, reactive, nextTick } from 'vue'
  // import Table from '../../../components/indexTable.vue'
  import * as api from "../../api/digital";
  import { ElMessageBox, ElMessage ,ElLoading } from "element-plus";
  import editAddStandardIndex from "../../technologyExamine/zjExamine/standardIndexLibrary/addAndEdit.vue";
  import scoreManModal from "../../technologyExamine/zjExamine/standardIndexLibrary/addAndEdit.vue";
  import { useRoute } from "vue-router";
  import { dataDictionary } from "@/api/dict";
  import pubFc from "@/views/examineManage/utils";
  import AddDialog from './addDialog.vue'
  import TagsView from '@/components/Layout/components/TagsView/index.vue'
  import { cloneDeep } from 'lodash'
  import {getManageList1} from "../../api/digital";
  const searchFrom = reactive({
    //查询
    param: "",
    current:1,
    size:20,
    bankId:"" as any ,
    id:"" as any ,
  });
  // const refreshPage:any=inject('refreshPage', Function, true);
  let standardType = ref("1"); //该参数决定显示的是中交还是中咨的标准库纸指标
  const route = useRoute();
  const assessmentTable = ref()

  standardType.value = route.meta.type as string;
  const status = ref<string>((route.query.status as string) ?? '');
  const cookie = () => localStorage.getItem('token')
  let data = reactive<any>({
    table_list: [],
    modalVisible: false,
    handleRowData: null, //正在处理的行数据
    scoreManVisible: false,
    table_loading: false,
    fustank: false,
    addType:'add',
    table_assessment:[],//考核table
    selectAssessment:[],//考核table  选中的数据
    fileList:[],
    headers: {
        Authorization: 'Bearer ' + cookie(),
      },
    searchIpt:'',//单位搜索文字
  });
  const dictDatas = reactive({
    dict_indexTypes: [],
    dict_indexNames: [],
    dict_scoreTypes: [],
    dict_scoreMethods: [],
    dict_scoreSources_zj: [],
    dict_scoreSources_zz: [],
    dict_scoreCompose_zj: [],
    dict_scoreCompose_zz: [],
  }); //字典值
  let selectedRows = ref<any>([]);
  const search = () => {
    //搜索
    gettargetlist();
  };
  //下载模板
  const downMb = () =>{
    api.downMb()
  }
  //模板导入
  const importMb = () =>{

  }
  const handleSuccess = (response, file, fileList) =>{
    if(response.code == 200){
        console.log('handleSuccess',response, file, fileList);
        console.log('--',file.raw);
        const formData = new FormData() as any;
        formData.append('bankId', route.query.bankId);
        formData.append('file', file.raw);
        api.importMb(formData).then(res =>{
            if(res.data.code == 200){
                if(res.data.msg == ''){
                  ElMessage.success('模板导入成功')
                }else{
                  ElMessage.success(res.data.msg)
                }
                gettargetlist();
            }
        })
        data.fileList = []
    }

  }
  const getExportBtn = () => {
    ElMessageBox.confirm("确定要批量导出吗?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
    //批量导出
    api
      .exportManageRequest({
        ...searchFrom,
      })
      .then((res) => {
        const { data, headers } = res;
        pubFc.downloadFunc(data, headers);
      });
    });
  };
  const multipleDevCreateRef = ref();
  const selectionChange = (arr) => {
    selectedRows.value = arr;
  };
  const handleDetect = () => {
    //批量删除

    if (!selectedRows.value?.length) {
      ElMessage({
        message: "请选择数据后删除！",
        type: "warning",
      });
    } else {
      ElMessageBox.confirm("确定要删除选中数据吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let ids = [] as any
        selectedRows.value.forEach(e  => {
          ids.push(e.id)
        });
        api
          .deleteManageRequest({
            ids: ids
          })
          .then((res) => {
            if (res.data.code == 200) ElMessage.success("删除成功");
            gettargetlist();
          });
      });
    }
  };

  const handleAdd = (type) => {
    //新增
    data.addType = "add";
    data.handleRowData = {};
    data.modalVisible = true;
  };
  const closeDialog = () =>{
    data.modalVisible = false
    gettargetlist();
  }

  //编辑
  const handleEdit = (item,type) => {
    data.addType = type
    data.handleRowData = item;
    data.modalVisible = true;
  };

  //---------生成考核
  const handleAssessment = () =>{
    if (selectedRows.value.length < 1) {
      ElMessage({
        message: "请选择一条数据数据",
        type: "warning",
      });
    } else {
      //
      api.getAssment().then(res =>{
        data.table_assessment = res.data.data
        data.assessmentVisible = true
      })
    }
  }
  //搜索单位
  const changeIpt = (val) =>{
    console.log('search ',val);
    api.getAssment().then(res =>{
        data.table_assessment = res.data.data.filter(e =>{
          return e.companyName.includes(val)
        })

      })
  }
  const closeAssessment = () =>{
    data.assessmentVisible = false
    assessmentTable.value.clearSelection()
  }
  //---------生成考核  保存
  const saveAssessment = () =>{
    let list = [] as any
    selectedRows.value.forEach(e =>{
      list.push(e.id)
    })
    if(data.selectAssessment.length < 1){
      ElMessage({
        message: "请选择一条数据数据",
        type: "warning",
      });
    } else {
      data.fustank = true;
      const loading = ElLoading.service({
        lock: true,
        text: '正在生成考核计划',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      data.table_loading = true;
      let obj = {
        bankId:route.query.bankId,
        questionIds:list,
        companyIds:data.selectAssessment,
      }
      api.saveAssment(obj).then(res =>{
        if(res.data.code == 200){
          ElMessage({
            message: "生成考核成功",
            type: "success",
          });
          data.fustank = false;
          loading.close()
          data.table_loading = false;
          closeAssessment()
          gettargetlist()
        }
      })
    }

  }
  //选择考核 多选
  const selectionAssessment = (val) =>{
    console.log('选择考核 多选',val);
    data.selectAssessment = []
    val.forEach(e =>{
      data.selectAssessment.push(e.id)
    })
  }

  const getDictDatas = () => {
    return new Promise((resolve, reject) => {
      data.table_loading = true;
      let dictIds = [
        "KHGL_CLASS_INDEX_NAME_CODE",
        "KHGL_INDEX_TYPE_CODE",
        "KHGL_SCORE_METHOD_CODE",
        "KHGL_SCORE_TYPE_CODE",
        "KHGL_ZJ_EXAMINE_SCORE_METHOD_CODE",
        "KHGL_ZZ_EXAMINE_SCORE_METHOD_CODE",
      ];
      dataDictionary(dictIds).then((res) => {
        let response = res.data.data;
        dictDatas.dict_indexTypes = response.KHGL_INDEX_TYPE_CODE;
        dictDatas.dict_indexNames = response.KHGL_CLASS_INDEX_NAME_CODE;
        dictDatas.dict_scoreTypes = response.KHGL_SCORE_TYPE_CODE;
        dictDatas.dict_scoreMethods = response.KHGL_SCORE_METHOD_CODE;
        dictDatas.dict_scoreSources_zj = response.KHGL_ZJ_EXAMINE_SCORE_METHOD_CODE;
        dictDatas.dict_scoreSources_zz = response.KHGL_ZZ_EXAMINE_SCORE_METHOD_CODE;
        if (standardType.value === "1") {
          //中交
          response.KHGL_ZJ_EXAMINE_SCORE_METHOD_CODE.map((item) => {
            dictDatas.dict_scoreCompose_zj = dictDatas.dict_scoreCompose_zj.concat(
              item.children
            );
          });
        } else {
          response.KHGL_ZZ_EXAMINE_SCORE_METHOD_CODE.map((item) => {
            dictDatas.dict_scoreCompose_zz = dictDatas.dict_scoreCompose_zz.concat(
              item.children
            );
          });
        }

        resolve(1);
      });
    });
  };
  // let table_list=reactive<any>([]);

  //获取标准指标库列表
  const gettargetlist = () => {
    searchFrom.bankId = route.query.bankId
    searchFrom.id = route.query.id
    data.table_loading = true;
    api
      .getManageList1({
        ...searchFrom,
      })
      .then((res) => {
        data.table_loading = false;
        const list = (res.data.data || []) as Record<string, any>[];
        const loopData = (data: Record<string, any>[], id = '') => {
          for (let i = 0; i < data.length; i++) {
            const line = data[i];
            if (id) line.parentId = id;
            const children = line.children;
            if (children?.length) loopData(children, line.id)
          }
        }
        loopData(list);
        data.table_list = list
      });
  };

  getDictDatas().then(() => {
    gettargetlist();
  });

  // 选择全部
  const selectAll = (selection: any[]) => {
    // tabledata第一层只要有在selection里面就是全选
    const isSelect = selection.some((el: any) => {
      const tableDataPaths = data.table_list.map((j: any) => j.id)
      return tableDataPaths.includes(el.id)
    })
    // tableDate第一层只要有不在selection里面就是全不选
    const isCancel = !data.table_list.every((el: any) => {
      const selectPaths = selection.map(j => j.id)
      return selectPaths.includes(el.id)
    })
    if (isCancel) {
      data.table_list.map((el: any) => {
        if (el.children) {
          // 解决子组件没有被勾选到
          setChildren(el.children, false)
        }
      })
    }
    if (isSelect) {
      selection.map(el => {
        if (el.children) {
          // 解决子组件没有被勾选到
          setChildren(el.children, true)
        }
      })
    }
  }

  // 选中父节点时，子节点一起选中/取消
  const select = (selection: any[], row: any) =>  {
    const hasSelect = selection.some((el: any) => {
      return row.id === el.id
    })
    if (hasSelect) {
      if (row.children) {
        // 解决子组件没有被勾选到
        setChildren(row.children, true)
      }
      // 子节点被全勾选，父节点也勾上
      setParent(row, true, [], selection)

    } else {
      if (row.children) {
        setChildren(row.children, false)
      }
      // 子级取消选中, 传入当前选中节点, 所有父级取消选中
      setParent(row, false, [], [])
    }
  }

  // 设置父级选中/取消
  const setParent = (currentRow: any, type: boolean, parent: any[], selectionLists: any[]) => {
    if (!parent.length) {
      parent = data.table_list
    }
    let allSelect: any[] = []
    parent.forEach((item: any) => {
      if (item.children) {
        // 注：Parent 是当前选中节点的所有父节点的一个字符串形式的数据，这个很关键
        if (currentRow.parentId === item.id) {
          // 选中
          if (type) {
            selectionLists.forEach((k: any) => {
              item.children?.forEach((j: any) => {
                if (k.id == j.id) {
                  allSelect.push(j)
                }
              })
            })
            if (allSelect.length == item.children.length) {
              toggleSelection(item, type)
              selectionLists.push(item)
              select(selectionLists, item)
            } else {
              setParent(currentRow, type, item.children, selectionLists)
            }
          } else {
            // 取消选中
            toggleSelection(item, type)
            setParent(currentRow, type, item.children, [])
          }
        }
      }
    })
  }


  const setChildren = (children: any[], type: boolean) => {
    // 编辑多个子层级
    children.map((j: any) => {
      toggleSelection(j, type)
      if (j.children) {
        setChildren(j.children, type)
      }
    })
  }
  const toggleSelection = (row: any, select: boolean) => {
    // 编辑多个子层级
    if (row) {
      nextTick(() => multipleDevCreateRef.value?.toggleRowSelection(row, select))
    }
  }
  </script>
  <style lang="scss" scoped>
  .container {
    background-color: white;
    padding: 20px;
    overflow-y: auto;
  }

  // :deep(.el-dialog__body) {
  //   padding: 0 !important
  // }
  :deep(.el-dialog__body) {
    padding: 0;
    height: 500px;
    overflow-y: scroll;
    overflow-x: auto;
  }

  .dialogCloseBtn {
    position: absolute;
    top: 20px;
    right: 20px;
  }

  // .el-col {
  //   line-height: 60px;
  // }

  .pageName {
    font-weight: 700;
  }

  .el-form-item {
    .el-input {
      width: 100px;
    }

    .el-select {
      width: 100px;
    }
  }
  .upload-demo{
    display: inline-block;
    width: 80px;
    margin: 0 10px;
  }

  :deep(.demo-tabs > .el-tabs__content) {
    max-height: 500px;
    overflow-y: scroll;
    scrollbar-width: none;
    /* Firefox */
    -ms-overflow-style: none;
    /* IE 10+ */
  }

  :deep(.demo-tabs > .el-tabs__content::-webkit-scrollbar) {
    display: none;
    /* Chrome Safari */
  }
  :deep .el-breadcrumb{
  margin-bottom: 15px;
  span{
    color: #606266;
  }
}
  </style>
